/**
 * 异常过滤器
 */
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { Logger } from 'nestjs-pino';
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(private readonly logger: Logger) {}
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();
    const error: any = exception.getResponse();
    console.log(error.message);

    this.logger.error(
      `time:${new Date().toISOString()},url:${request.url},message:${
        error.message
      }`,
    );
    response.status(status).json({
      code: error.code,
      timestamp: new Date().toISOString(),
      path: request.url,
      message: error.message,
    });
  }
}
